package com.auto.reg.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;

public class CmdUtil {
	
	private static final String clearCacheCmd = 
			"cmd /K set \"z=HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders\" & " +
			"for %a in (cache history cookies) do ( for /f \"tokens=2*\" %b in (\'reg query \"%z%\" /v %a\') " +
			"do (if exist \"%c\" (rd /s /q \"%c\" & md \"%c\")))";

	public static void cleanIECache() {
		CmdUtil.executeCommand(clearCacheCmd);
	}
	
	public static String executeCommand(String command) {

		StringBuffer result = new StringBuffer();
		BufferedReader readStream = null;
		try {
			Process process = Runtime.getRuntime().exec(command);
			readStream = new BufferedReader(new InputStreamReader(process.getInputStream()));
			result.append(readStream.readLine()); 		
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result.toString();
	}
	
	public static void changeOSProductId() {
    
		String oid = RefreshRegInfoUtil.generateFakeOID();
	    String editReg = RegConstant.REG_EDIT_CMD.replace("$", oid);
	    executeCommand(editReg);
	}

	public static void openDownloadHtml() {

		File file = new File(RegConstant.DOWNLOAD_HTML);
		String openCmd = file.getAbsolutePath();
		System.out.println(openCmd);

		executeCommand("cmd.exe /c start " + openCmd);
	}
	
	public static void openUrlInExplore(String url) {

		Properties properties = System.getProperties();
        String osName = properties.getProperty("os.name");
         
        System.out.println (osName);
         
        try {
        	if (osName.indexOf("Linux") != -1) {
                Runtime.getRuntime().exec("htmlview");
            } else if (osName.indexOf("Windows") != -1){
                Runtime.getRuntime().exec("cmd /c start " + url);
            } else {
                throw new RuntimeException("Unknown OS.");
            }
		} catch (Exception e) {
			e.printStackTrace();		
		}
	}

	public static void main(String[] args) {

		Timer timer = new Timer(false);
		WorkerTask task = new CmdUtil().new WorkerTask("auto.exe");
		timer.scheduleAtFixedRate(task, 0, 5000);
//		CmdUtil.openUrlInExplore("https://appleid.apple.com/cgi-bin/WebObjects/MyAppleId.woa/wa/createAppleId?localang=zh_CN");
//		cleanIECache();
		
	}

	public static boolean findProcess(String processName){
        BufferedReader br=null;
        try{

            Process proc=Runtime.getRuntime().exec(" tasklist /fi \" imagename eq "   + processName + " \" ");   
            br=new BufferedReader(new InputStreamReader(proc.getInputStream()));   
            String line=null;   
            while((line=br.readLine())!=null){   
                if(line.contains(processName)){   
                    return true;   
                }
            }

            return false;
        }catch(Exception e){
            e.printStackTrace();   
            return false;   
        }finally{   
            if(br!=null){   
                try{   
                    br.close();   
                }catch(Exception ex){   
                }
            }
        }
    }

	class WorkerTask extends TimerTask {
		
		private String processName;
		private int counter;
		
		public WorkerTask(String processName) {
			this.processName = processName;
			this.counter = 1;
		}

		@Override
		public void run() {

			if (counter < 0) {
				CmdUtil.changeOSProductId();
				CmdUtil.executeCommand(RegConstant.CHANGE_MAC_EXE);
				counter = 1;
			} else {
				if (CmdUtil.findProcess(processName) == false && CmdUtil.findProcess("change_mac.exe") == false) {
	            	RefreshRegInfoUtil.refreshIni();
	            	CmdUtil.executeCommand(RegConstant.REG_EXE);
	            }
				counter --;
			}
		}
	}
	
}
